package com.gl.ruanzhu.util;


import org.apache.axis.encoding.Base64;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.NoSuchAlgorithmException;


public class downFileUtil {

    public static  void download(String path,String fileName, HttpServletResponse response) {

        // 读到流中
        InputStream inStream = null;// 文件的存放路径
        try {
            inStream = new FileInputStream(path+fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void downFile(String url, String id, String leixing,//wid:文档编号,dbName:文件名，source：资源 docTitle：文档标题
                                 HttpServletRequest request,
                                HttpServletResponse response) throws NoSuchAlgorithmException,
            IOException {
        String download_url = "http://124.235.216.250:8082/api/SubstaskInformation/DownloadHTHT";

        id = "537";
        leixing="ZRWFJ";

        download_url += "?taskID=" + 537 + "&leixing=" + "ZRWFJ";
        downLoadFromUrl(download_url, "docTitle" + ".zip", "C:\\download",
                null, null, response);
    }

    /**
     * 从Url中下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */

    public static void downLoadFromUrl(String urlStr, String fileName,
                                       String savePath, String download_appcode, String download_appkey,
                                       HttpServletResponse response) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置超时间为3秒
        conn.setConnectTimeout(60 * 1000);
        // 防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // conn.setRequestProperty("lfwywxqyh_token",token);
        conn.setRequestProperty("Authorization", "APPCODE " + download_appcode);
        conn.setRequestProperty("X-Ca-AppKey", download_appkey);
//        conn.setRequestProperty("C ontent-Type", "application/pdf;charset=UTF-8");
        // 得到输入流
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//        String xmlHead = "";
//        String xmlContent="";
        String line = null;


//        InputStream inputStream = conn.getInputStream();
//        OutputStream outputStream = conn.getOutputStream();
        StringBuffer sb = new StringBuffer();
        // 获取自己数组  
        while ((line = in.readLine())!= null) {
            sb.append(line);
        }
//        byte[] bs = readInputStream(inputStream);
//        String s1=bs.toString();
//        String data = new String(bs);
        String data = sb.toString();
        ;
        response.setContentType("application/pdf;charset=UTF-8");
        BufferedOutputStream output = null;
        BufferedInputStream input = null;
        try {
            output = new BufferedOutputStream(response.getOutputStream());
            // 中文文件名必须转码为 ISO8859-1,否则为乱码
            String fileNameDown = new String(fileName.getBytes(), "ISO8859-1");
            // 作为附件下载
            response.setHeader("Content-Disposition", "attachment;filename="
                    + fileNameDown);
            byte[] bytes = Base64.decode(data);
            output.write(bytes);
            response.flushBuffer();
        } catch (Exception e) {
            // log.error("Download log file error", e);
        } // 用户可能取消了下载
        finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (output != null)
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    /**
     * 获取token
     *
     * @param appid
     * @param request
     * @param response
     * @throws IOException
     */

    public static String gettoken(String appid, HttpServletRequest request,
                                  HttpServletResponse response) throws IOException {

        String result = "";
        BufferedReader bufferedReader = null;
        PrintWriter out = null;
        try {
            //1、2、读取并将url转变为URL类对象
            URL realUrl = new URL("http://api.kefuju.cn/claimToken?name=chengduguolong&password=chengduguolong&api_id=" + appid);

            //3、打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            //4、设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //5、建立实际的连接
            //connection.connect();
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            //发送请求参数
            out.print(appid);
            //flush输出流的缓冲
            out.flush();
            //

            //6、定义BufferedReader输入流来读取URL的响应内容
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while (null != (line = bufferedReader.readLine())) {
                result += line;
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("发送POST请求出现异常！！！" + e);
            e.printStackTrace();
        } finally {        //使用finally块来关闭输出流、输入流
            try {
                if (null != out) {
                    out.close();
                }
                if (null != bufferedReader) {
                    bufferedReader.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream)
            throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}
